using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using E4RPTools;
using StationCommon;

namespace Station.Controls
{
    public partial class MechanicXtraForm : XtraForm
    {
        private long _mechanicId;
        private MecanicoDataSet _mechanic;
        private Controller _controller;

        #region Properties

        public long MechanicId
        {
            set { _mechanicId = value; }
        }

        public Controller Controller
        {
            set { _controller = value; }
        }

        #endregion

        public MechanicXtraForm()
        {
            InitializeComponent();
            Load += MechanicXtraForm_Load;
            oKSimpleButton.Click += oKSimpleButton_Click;
        }

        #region Private Methods

        private void SetMechanicData()
        {
            _mechanic = new MecanicoDataSet();
            if (_mechanicId <= 0)
            {
                MecanicoDataSet.MecanicoRow mechanic = _mechanic.Mecanico.NewMecanicoRow();
                mechanic.Id = _mechanicId;
                mechanic.Nome = "";
                _mechanic.Mecanico.AddMecanicoRow(mechanic);
            }
            else
                _mechanic.Merge(_controller.GetMechanic(_mechanicId));            
        }

        

        private void GetDataFromControls()
        {
            _mechanic.Mecanico[0].Nome = nameTextEdit.Text;            
        }

        private void SetDataToControls()
        {
            nameTextEdit.Text = _mechanic.Mecanico[0].Nome;            
        }

        private void ClearControlErrors()
        {
            dxErrorProvider.SetError(nameTextEdit, "");            
        }

        private Control GetControl(string reference)
        {
            switch (reference)
            {
                case "Nome":
                    return nameTextEdit;
                default:
                    return null;
            }
        }

        private void SetControlErrors(Result result)
        {
            foreach (Error error in result.Errors)
                dxErrorProvider.SetError(GetControl(error.Reference), error.Message);
        }

        #endregion Private Methods

        void MechanicXtraForm_Load(object sender, EventArgs e)
        {
            SetMechanicData();
            SetDataToControls();
        }

        void oKSimpleButton_Click(object sender, EventArgs e)
        {
            ClearControlErrors();
            GetDataFromControls();
            Result result = _controller.IsMechanicValid(_mechanic.Mecanico[0]);
            if (result.Failed)
            {
                DialogResult = DialogResult.None;
                SetControlErrors(result);
            }
            else
                _controller.SaveMechanic(_mechanic.Mecanico[0]);
        }
    }
}